package com.avanty.spbnetty.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.CharsetUtil;

public class EchoServer {

	/**
	 * 用于分配处理业务线程的线程组个数
	 */
	private final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors() * 2;        //默认
	/**
	 * 业务出现线程大小
	 */
	private final int BIZTHREADSIZE = 4;
	private final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
	private final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);
	private ChannelFuture f = null;

	public void start(int port) {
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(bossGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					.option(ChannelOption.SO_BACKLOG, 100)
					.handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
                            pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
                            pipeline.addLast(new EchoHandler());
                        }
                    });

			f = bootstrap.bind(port);

		} catch (Exception e) {
			f.channel().closeFuture();
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
			e.printStackTrace();
		}
	}

	public void shutdown(){
		f.channel().closeFuture();
		bossGroup.shutdownGracefully();
		workerGroup.shutdownGracefully();
	}

	public static void main(String[] args){
		new EchoServer().start(1234);
	}

}
